<template>
  <div>
    <el-dialog
        title="操作选项"
        :visible.sync="dialogVisible"
        width="30%"
        @close="dialogVisible = false">
      <el-button type="primary" @click="dialogVisible1 = true">修改密码</el-button>
      <el-button type="danger" v-if="this.userInfo.isRemember===1" @click="resetPassword">重置密码</el-button>
      <el-button type="warning" v-if="this.userInfo.isAction===1"  @click="banUser">封禁</el-button>
      <el-button type="success" v-else-if="this.userInfo.isAction===0" @click="unbanUser">解禁</el-button>
      <el-button @click="dialogVisible = false">取消</el-button>
    </el-dialog>
    <el-dialog
        title="修改密码"
        :visible.sync="dialogVisible1"
        width="30%"
    >
      <el-form :model="form" ref="form" :rules="rules" label-width="80px">
        <el-form-item label="旧密码" prop="oldPassword">
          <el-input v-model="form.oldPassword"  show-password type="password"></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="form.newPassword" show-password type="password"></el-input>
        </el-form-item>
        <el-form-item label="确认密码"  prop="confirmPassword">
          <el-input v-model="form.confirmPassword"  show-password type="password"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm">提交</el-button>
          <el-button @click="dialogVisible1 = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-col :span="6">
      <el-input v-model="searchUser" placeholder="请输入搜索内容" @input="handleSearch"></el-input>
    </el-col>
    <el-col :span="2">
      <el-button type="primary" @click="handleSearch">搜索</el-button>
    </el-col>

    <el-table
        ref="multipleTable"
        :data="userList"
        :cell-style="{'text-align':'center'}"
        :header-cell-style="{'text-align':'center'}"
        tooltip-effect="dark"
        v-model="multipleSelection"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        @selection-change="handleSelectionChange">

      <el-table-column
          prop="userName"
          label="用户名"
          width="180"
      >
      </el-table-column>
      <el-table-column
          label="身份"
          width="180"
      >
        <template slot-scope="scope">
          <span v-if="scope.row.permissions===2">唯一管理</span>
          <span v-else-if="scope.row.permissions===1">用户</span>
        </template>
      </el-table-column>
      <el-table-column
            prop="userMail"
            label="用户邮箱"
            width="300"
      >
      </el-table-column>
      <el-table-column
          prop="creatDate"
          label="注册时间"
          width="180"
      >
      </el-table-column>
      <el-table-column
          prop="loginDate"
          label="上一次登录时间"
          width="180"
      >
      </el-table-column>
      <el-table-column
          prop="creatDate"
          label="注册事件"
          width="180"
      >
      </el-table-column>
      <el-table-column
          label="状态"
          width="100"
      >
        <template slot-scope="scope">
        <span v-if="scope.row.isAction===1">未禁用</span>
        <span v-else-if="scope.row.isAction===0">已禁用</span>
        </template>

      </el-table-column>
      <el-table-column
          label="密码"
          width="100"
      >
        <template slot-scope="scope">
          <span v-if="scope.row.isRemember===1">已忘记</span>
          <span v-else-if="scope.row.isRemember===0">未忘记</span>
        </template>

      </el-table-column>
      <el-table-column
          label="操作"
          width="180"
      >
        <template slot-scope="scope">
          <el-button v-if="scope.row.userName !== 'root'" @click="handleEdit(scope.$index, scope.row)" type="primary" size="small">编辑</el-button>
          <el-button v-if="scope.row.userName !== 'root'" @click="handleDelete(scope.$index, scope.row)" type="danger" size="small">删除</el-button>
        </template>

      </el-table-column>


    </el-table>
    <!-- Element UI分页器 -->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
    ></el-pagination>

  </div>
</template>
<script>
import axios from "axios";

export default {
  data() {
    var validateOldPass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.userInfo.userPass) {
        callback(new Error('旧密码输入错误!'));
      } else {
        callback();
      }
    };
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.form.newPassword) {
        callback(new Error('两次输入的密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      userInfo:{
        userId:'',
        userName:'',
        userPass:''
      },
      multipleSelection: [],
      userList: [], // 邮件列表
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页显示数量
      total: 0, // 总数
      unreadEmails: 0, // 总邮件数
      drag: false,
      searchUser:'',
      dialogVisible:false,
      dialogVisible1:false,
      form: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: '',
      },
      rules:{
        oldPassword: [
          { required: true, message: '请输入旧密码', trigger: 'blur' },
          {validator: validateOldPass, trigger: ['blur', 'change'] }
        ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
        ],
        confirmPassword: [
          { required: true, message: '请再次输入新密码', trigger: 'blur' },
          { validator: validatePass, trigger: ['blur', 'change'] }
        ],
      }
    };
  },
  watch:{
    searchUser(newVal, oldVal) {
      // 当 searchUser 发生变化时，调用 getUserList 方法
      if (newVal !== oldVal) {
        this.getUserList();
      }
    }

  },
  created() {
    this.getUserList();
  },
  methods: {
    getUserList(){
      axios.get('http://localhost:8989/user/list',{
        params: {
          key: this.searchUser,
          pageNum: this.currentPage,
          pageSize: this.pageSize,
        },
      }).then(res=>{
            console.log(res.data.records)
        this.userList = res.data.records;
        // this.userList = this.userList.slice(1)
            this.total = res.data.total;
          }).catch(err=>{

      })
    },

    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.getUserList();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getUserList();
    },
    handleSearch(){
      this.getUserList();
    },
    handleDelete(index, row) {
      console.log(row)
      this.userInfo.userId=row.userId;
      this.userInfo.userName=row.userName;
      this.userInfo.userPass=row.userPass;
      this.$confirm('此操作将删除该用户及邮箱, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteUser();
        this.userInfo = {
          userId: '',
          userName: '',
          userPass: ''
        };
      })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            });
          });
    },
    handleEdit(index,row) {
      this.userInfo.userId=row.userId;
      this.userInfo.userName=row.userName;
      this.userInfo.userPass=row.userPass;
      this.userInfo.isAction=row.isAction;
      this.userInfo.isRemember=row.isRemember;

      this.dialogVisible = true;
    },
    submitForm(){
      console.log("提交")
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.changePassword();
          this.userInfo = {
            userId: '',
            userName: '',
            userPass: '',
            isAction: '',
            isRemember: '',
          };
          this.$router.push('/user')
        }
      });
    },
    changePassword(){
      console.log(this.userInfo.userId);
      axios.post('http://localhost:8989/user/changePassword', {
        userId: this.userInfo.userId,
        userName: this.userInfo.userName,
        userPass: this.form.newPassword,
      })
          .then((response) => {
            console.log(response.data);
            this.dialogVisible1 = false;
            this.dialogVisible=false;
            this.$message({
              message: '修改成功',
              type: 'success'
            });

          })
          .catch((error) => {
            this.$message({
              message: '修改失败',
              type: 'error'
            });
          })

    },
    resetPassword(){
      console.log(this.userInfo.userId);
      axios.post('http://localhost:8989/user/changePassword', {
        userId: this.userInfo.userId,
        userName: this.userInfo.userName,
        userPass: "123456",
      })
          .then((response) => {
            console.log(response.data);
            this.dialogVisible=false;
            this.reset();
          })
          .catch((error) => {
            this.$message({
              message: '重置失败',
              type: 'error'
            })
          })
    },
    reset(){
      axios.post('http://localhost:8989/user/resetPassword', {
        userId: this.userInfo.userId,
        userName: this.userInfo.userName,
      })
          .then((response) => {
            console.log(response.data);
            this.$router.go(0)
            this.$message({
              message: '重置成功',
              type: 'success'
            });
          })
          .catch((error) => {
            this.$message({
              message: '重置失败',
              type: 'error'
            })
          })
    },
    logout(){
      this.$confirm('此操作将退出账号, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$store.commit('logout');
        this.$router.push({ path: '/' });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },
    banUser(){
      this.$confirm('此操作将封禁账号, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.post('http://localhost:8989/user/banUser', {
          userId: this.userInfo.userId,
          userName: this.userInfo.userName,
        })
            .then((response) => {
              console.log(response.data);
              this.$router.go(0)
              this.$message({
                message: '封禁成功',
                type: 'success'
              });
            })
            .catch((error) => {
              this.$message({
                message: '封禁失败',
              })
            })
      });
    },
    unbanUser(){
      this.$confirm('此操作将解封账号, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.post('http://localhost:8989/user/unBanUser', {
          userId: this.userInfo.userId,
          userName: this.userInfo.userName,
        })
            .then((response) => {
              console.log(response.data);
              this.dialogVisible=false;
              this.$router.go(0)
              this.$message({
                message: '解封成功',
                type: 'success'
              });
            }).catch((error) => {
              this.$message({
                message: '解封失败',
              })
        })
          })
    },

    deleteUser(){
      this.$confirm('此操作将注销账号, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log("deleteUser");
        console.log(this.userInfo);
        axios.post('http://localhost:8989/user/deleteUser',
            {
              userId: this.userInfo.userId,
              userName: this.userInfo.userName,
              userPass: this.userInfo.userPass,
            })
            .then(res => {
              this.$message({
                type: 'success',
                message: '注销成功!'
              });
              this.$router.go(0)
            }).catch(res=> {
          this.$message({
            type: 'error',
            message: '注销失败!'
          });
        });

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },


  }

}
</script>